package com.lovo.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.lovo.common.bean.Order;
import com.lovo.common.result.GlobalHandleException;
import com.lovo.common.result.ResponseResult;
import com.lovo.common.result.ResultCode;
import com.lovo.common.util.MQUtil;
import com.lovo.common.util.RedisUtil;
import com.lovo.order.form.OrderForm;
import com.lovo.order.service.OrderService;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@ResponseResult
@RequestMapping("/orders")
@Tag(name = "订单控制器OrderController")
@SecurityRequirement(name = "bearer-key")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private MQUtil mqUtil;

    @PostMapping
    public Object addOrder(@RequestBody OrderForm orderForm){
        Order order = new Order();
        BeanUtils.copyProperties(orderForm,order);
        System.out.println(order);
        orderService.addOrder(order);
        return null;
    }

    @GetMapping("/seckill")
    public Object seckill(Integer userId,Integer productId) throws GlobalHandleException {
        // 判断库存
        Object productCount = redisUtil.get("product_" + productId);
        if(productCount == null || Integer.parseInt(productCount.toString()) <= 0){
            throw new GlobalHandleException(ResultCode.COMMODITY_NOT_ENOUGH);
        }
        mqUtil.send("shop.direct.exchange","rk.seckill",userId + "," + productId);
        return null;
    }
}
